package com.budayi.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.budayi.common.utils.OssClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

/**
 * @author LIBOFEI
 * @ClassName TestController
 * @description
 * @date 2021/4/22 22:05
 * @Version 1.0
 **/
@RestController
public class TestController {

    @Autowired
    private OssClientUtil ossClientUtil;


    @RequestMapping("/test/upload")
    public String testUploadFile(){
        String url = ossClientUtil.uploadByFile("budayi-img",new File("/Users/mac/Pictures/pap.er/f-rticEjF0E.jpg"));
        return url;
    }


    public static void main(String[] args) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI5t7dKYNR9xRgpi9bRv3F";
        String accessKeySecret = "ZuFCCv8mFfSGcDtZRDIigyjpPKrXNa";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


        // 创建存储空间。
//        ossClient.createBucket("bduayi-img");

        String bucketName = "budayi-img";


        if(!ossClient.doesBucketExist(bucketName)){
            CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }

        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = "20210423/logo.jpg";
        File file = new File("/Users/mac/Pictures/pap.er/f-rticEjF0E.jpg");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,objectName, file);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        putObjectRequest.setMetadata(metadata);

// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传文件。
        ossClient.putObject(putObjectRequest);

        System.out.println(objectName);

        // 关闭OSSClient。
        ossClient.shutdown();

    }
}
